const { app, BrowserWindow, Menu, Tray, ipcMain, net } = require('electron')
const path = require('path')

var window1 = null
var window2 = null
var window3 = null

var window1_unfold = false


/* 创建窗口函数 */
function createWindow1 () {
  window1 = new BrowserWindow({
    width: 150,
    height: 150,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, "src", "assets", "app.png"),
    frame: false,
    skipTaskbar: true,
    resizable: false,
    alwaysOnTop: false,
    transparent: true,
    movable: false,
    fullscreenable: false
  })
  // window1.loadURL("http://localhost:8080")
  window1.loadFile(path.join(__dirname, "dist", "index.html"))
  setTimeout(() => {
    window1.webContents.send("route-to-page", { url: "/player" });
  }, 5000)

  appIcon = new Tray(path.join(__dirname, "src", "assets", "app.png"))
  const contextMenu = Menu.buildFromTemplate([
    { label: '改变形态', type: 'normal', click: () => { 
        window1_unfold = !window1_unfold
        if (window1_unfold === true) {
          window1.setSize(300, 120)
        } else {
          window1.setSize(150, 150)
        }
        window1.webContents.send('response-to-change-player-form', { unfold: window1_unfold })
      } },
    { label: '移动窗口', type: 'normal', click: () => { createWindow3() } },
    { label: '打开音乐列表', type: 'normal', click: () => { createWindow2() } },
    { label: '退出', type: 'normal', click: () => { app.quit() } }
  ])
  appIcon.setContextMenu(contextMenu)
  appIcon.on('double-click', () => { window1.show() })
}


function createWindow2 () {
  window2 = new BrowserWindow({
    width: 900,
    height: 500,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, "src", "assets", "app.png"),
    skipTaskbar: false,
    autoHideMenuBar: true
  })
  // window2.loadURL("http://localhost:8080")
  window2.loadFile(path.join(__dirname, "dist", "index.html"))
  setTimeout(() => {
    window2.webContents.send("route-to-page", { url: "/musiclist" });
  }, 3000)
}


function createWindow3 () {
  window3 = new BrowserWindow({
    width: 400,
    height: 250,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, "src", "assets", "app.png"),
    skipTaskbar: false,
    autoHideMenuBar: true
  })
  // window3.loadURL("http://localhost:8080")
  window3.loadFile(path.join(__dirname, "dist", "index.html"))
  setTimeout(() => {
    window3.webContents.send("route-to-page", { url: "/modifylocation" });
  }, 3000)
}


/* app 触发事件 */
app.on('ready', () => {
  createWindow1()
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow1()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})


/* 进程通信事件 */
ipcMain.on("get-allmusic", (event, message) => {
  console.log("get allmusic...")
  const request = net.request('http://music.ma-jing.cn/api/allmusic')
  request.on('response', (response) => {
    response.on("data", (chunk) => {
      var data = JSON.parse(chunk)
      if (data['status'] === "success") {
        event.reply('response-to-get-allmusic', { status: "success", data: data['data'], explain: "success" })
      } else {
        console.log(data)
        event.reply('response-to-get-allmusic', { status: 'error', data: [], explain: 'error' })
      }
    })
    response.on("end", () => {
      console.log("...data receive complete")
    })
  })
  request.on('error', (err) => {
    console.error(err)
    event.reply('response-to-get-allmusic', { status: 'error', data: [], explain: 'error' })
  })
  request.end()
})


ipcMain.on("get-music-id", (event, message) => {
  console.log("get music with id " + message.id + "...")
  const request = net.request('http://music.ma-jing.cn/api/music?id=' + message.id)
  request.on('response', (response) => {
    response.on("data", (chunk) => {
      var data = JSON.parse(chunk)
      if (data['status'] === "success") {
        event.reply('response-to-get-music-id', { status: "success", data: data['data'], explain: "success" })
      } else {
        console.log(data)
        event.reply('response-to-get-music-id', { status: 'error', data: {}, explain: 'error' })
      }
    })
    response.on("end", () => {
      console.log("...data receive complete")
    })
  })
  request.on('error', (err) => {
    console.error(err)
    event.reply('response-to-get-music-id', { status: 'error', data: {}, explain: 'error' })
  })
  request.end()
})


ipcMain.on('pick-music', (event, message) => {
  console.log("pick music with bv " + message.bv)
  const request = net.request('http://music.ma-jing.cn/api/pickmusic?bv=' + message.bv)
  request.on('response', (response) => {
    response.on("data", (chunk) => {
      var data = JSON.parse(chunk)
      if (data['status'] === "success") {
        event.reply('response-to-pick-music', { status: "success", data: 'success', explain: "success" })
      } else {
        console.log(data)
        event.reply('response-to-pick-music', { status: 'error', data: 'error', explain: 'error' })
      }
    })
    response.on("end", () => {
      console.log("...data receive complete")
    })
  })
  request.on('error', (err) => {
    console.error(err)
    event.reply('response-to-pick-music', { status: 'error', data: 'error', explain: 'error' })
  })
  request.end()
})

ipcMain.on('change-player-form', (event, message) => {
  window1_unfold = message.unfold
  if (window1_unfold === true) {
    window1.setSize(300, 120)
  } else {
    window1.setSize(150, 150)
  }
  event.reply('response-to-change-player-form', message)
})

ipcMain.on('open-music-list', (event, message) => {
  createWindow2()
})

ipcMain.on('change-new-music', (event, message) => {
  window1.webContents.send('wait-to-change-new-music', message)
})

ipcMain.on('change-player-location', (event, message) => {
  window1.setPosition(parseInt(message.x), parseInt(message.y))
})

ipcMain.on('quit-app', (event, message) => {
  app.quit()
})